package com.android.multiplesmart.activity;

import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ScrollView;
import android.widget.Toast;


import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.android.multiplesmart.DemoApplication;
import com.android.multiplesmart.R;
import com.android.multiplesmart.adapter.MainAdapter;
import com.android.multiplesmart.adapter.SpinngerAdapter;

import com.android.multiplesmart.bean.CodeBean;
import com.android.multiplesmart.bean.LaguageAllBean;
import com.android.multiplesmart.bean.LanguageBean;
import com.android.multiplesmart.bean.LanguageDataBean;
import com.android.multiplesmart.bean.LanguageTypeBean;
import com.android.multiplesmart.bean.LocaLanguageBean;
import com.android.multiplesmart.bean.MainFinalTeachingBean;
import com.android.multiplesmart.bean.MainPauseTeachingBean;
import com.android.multiplesmart.bean.MainStudentBean;
import com.android.multiplesmart.bean.MainTeachingBean;
import com.android.multiplesmart.bean.MianReBean;
import com.android.multiplesmart.bean.PageInfoBean;
import com.android.multiplesmart.bean.PdfurlBean;
import com.android.multiplesmart.bean.ResponseSpeechBean;
import com.android.multiplesmart.bean.Servicess;
import com.android.multiplesmart.databinding.ActivitysMainBinding;
import com.android.multiplesmart.downfiles.DownloadUtil;
import com.android.multiplesmart.downfiles.FileUtil;
import com.android.multiplesmart.downfiles.FileVo;
import com.android.multiplesmart.downfiles.RxUtils;
import com.android.multiplesmart.utils.ActivityUtils;
import com.android.multiplesmart.utils.LanguageUtils;
import com.schillerchina.baselibrary.bean.CurrencyBean;
import com.schillerchina.baselibrary.constans.AppConstants;
import com.schillerchina.baselibrary.utils.GsonUtil;
import com.schillerchina.baselibrary.utils.Pref;
import com.schillerchina.baselibrary.utils.ToastUtil;
import com.android.multiplesmart.websocket.JWebSocketClient;
import com.android.multiplesmart.websocket.JWebSocketClientService;
import com.android.multiplesmart.utils.SpeechTransUtils;
import com.tencent.smtt.sdk.TbsReaderView;
import com.tencent.tbs.reader.ITbsReader;
import com.tencent.tbs.reader.ITbsReaderCallback;
import com.tencent.tbs.reader.TbsFileInterfaceImpl;


import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 翻译工具页面
 */
public class MainActivitys extends BaseActivity implements
        TbsReaderView.ReaderCallback, SpinngerAdapter.OnCallAdapter,View.OnTouchListener {

    public String action;
    private JWebSocketClient client;
    private JWebSocketClientService.JWebSocketClientBinder binder;
    private JWebSocketClientService jWebSClientService;
    private ActivitysMainBinding activitysMainBinding;
    private boolean isBind = false;
    private String officeUrl="";
    private String officeSaveName="";
    private String tbsReaderTemp = Environment.getExternalStorageDirectory() + "/TbsReaderTemp";
    String pdf_url = "";
    String langCode ="";
    String docNames="";
    DownloadUtil downloadUtil;
    TbsReaderView  tbsReaderView;

    private File file;
    private File files;
    private String username;
    private  String language_Name;
    private String languageDataBean;
    private String teacher_curriculum;
    private String allallLaguage;
    private SpinngerAdapter spinngerAdapter;
    ///语种
    private List<LocaLanguageBean> language=new LinkedList<>();
    private String Tag="MainActivitys";
    ///获取学生的语种
    private LanguageDataBean languageDataBeans;
    ///需要翻译的所有语言
    private ArrayList<LanguageDataBean>  allLanguage;
    ///获取老师和课程
    private LanguageTypeBean languageTypeBean;
    ///删选出来要翻译的语言
    private List<String> translation_language=new LinkedList<>();
    private List<MianReBean> mianReBeans=new LinkedList<>();
    private LaguageAllBean laguageAllBean;
    private int state=0;
    private String hashCode;

    public  int MIN_CLICK_DELAY_TIME = 5000;
    long upTime =0;
    long downTime =0;
    @RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activitysMainBinding = DataBindingUtil.setContentView(this, R.layout.activitys_main);
        //初始化语音和语言
        username=getIntent().getStringExtra(AppConstants.USER_NAME);
        language_Name=getIntent().getStringExtra(AppConstants.STUDENT_LANGUAGES);
        languageDataBean=getIntent().getStringExtra(AppConstants.SELECT_LANGUAGES);
        teacher_curriculum=getIntent().getStringExtra(AppConstants.TEACHER_CURRICULUM);
        allallLaguage= getIntent().getStringExtra(AppConstants.All_LANGUAGES);

        ///转换成实体类
        languageDataBeans= GsonUtil.GsonToBean(languageDataBean,LanguageDataBean.class);
        allLanguage= GsonUtil.getDataList(language_Name,LanguageDataBean.class);
        languageTypeBean= GsonUtil.GsonToBean(teacher_curriculum, LanguageTypeBean.class);
        laguageAllBean=GsonUtil.GsonToBean(allallLaguage, LaguageAllBean.class);
        System.out.println(languageTypeBean.getData().getTeacherLanguage().getLinkCode()+"获取数据");

        initView();
        initListener();
        initWebSocket();
        hashCode= Pref.getString(AppConstants.hashCode,"");
        onSend("{\"Cmd\":\"SpeechFinished\",\"Data\":{}}");
        if (Servicess.getService().getjWebSClientService().getStopState()==1){
             stop="1";
        }else {
             stop="";
        }
//      downLoad("en");
    }

    int reState=1;
    Bundle b = new Bundle();
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.word:
                break;
            case R.id.teacher:
//                if (statess==1){
//                    docName="test.txt";
//                    statess=2;
//                    kejian();
//                } else {
//                    docName="哈哈哈哈.txt";
//                    statess=1;
//                    kejian();
//                }
                break;
            case  R.id.shuaxin:
                if (stop.equals("1")){
                   DemoApplication.getHandlerUtils().saveCrashInfo2File("刷新课件");
                   onSend("{\"Cmd\":\"JoinClassroom\",\"Data\":{}}");
                }else {
                   ToastUtil.showToast("Unable to refresh during course pause");
                }
                break;
            case R.id.shang:
                b.putInt("progress", curPageIndex - 1);
                TbsFileInterfaceImpl.getInstance().gotoPosition(b);

                break;
            case R.id.xia:
                b.putInt("progress", curPageIndex + 1);
                TbsFileInterfaceImpl.getInstance().gotoPosition(b);
                break;
        }
    }



    @Override
    public void initListener() {
        activitysMainBinding.word.setOnClickListener(this);
        activitysMainBinding.button.setOnTouchListener(this);
        activitysMainBinding.teacher.setOnClickListener(this);
        activitysMainBinding.shuaxin.setOnClickListener(this);
        activitysMainBinding.shang.setOnClickListener(this);
        activitysMainBinding.xia.setOnClickListener(this);
    }

    private File filess;
    private MainTeachingBean mainTeachingBean;
    private SpeechTransUtils speechTransUtils;
    @Override
    public void initView() {
        activitysMainBinding.studenttext.setText(username+":");
        if (Build.VERSION.SDK_INT >= 29) {
            files = getExternalFilesDir("text");
        } else {
            files = Environment.getExternalStorageDirectory();
        }
        filess=new File(files,"xianshi.docx");
        initRe(username);
        ///展示信息
        activitysMainBinding.teacher.setText(languageTypeBean.getData().getCourse()+"  /  " +languageTypeBean.getData().getTeacher());
//      activitysMainBinding.curriculum.setText("课程:  " +languageTypeBean.getData().getCourse());
        activitysMainBinding.student.setText(username);

        ///获取点击的第一个
        for (int i=0;i<allLanguage.size();i++){
            String  LanguageCode=allLanguage.get(i).getLanguageCode();//翻译的code
            String  LinkCode=allLanguage.get(i).getLinkCode();//发音的code
            String  LanguageEnName=allLanguage.get(i).getLanguageEnName();//名称
            language.add(new LocaLanguageBean(LanguageCode,LinkCode,LanguageEnName));
            System.out.println(LinkCode+"获取数据呃呃呃呃呃呃");
        }

        for(int i=0;i<language.size();i++){
             if(language.get(i).getLanguageCode().equals(languageDataBeans.getLanguageCode())){
                 String LanguageCode=language.get(i).getLanguageCode();
                 String LinkCode=language.get(i).getLinkCode();
                 String LanguageEnName=language.get(i).getLanguageEnName();
                 language.remove(i);
                 language.add(0,new LocaLanguageBean(LanguageCode,LinkCode,LanguageEnName));
             }
        }
        System.out.println(GsonUtil.GsonString(language));
         languageName=language.get(0).getLinkCode();
        ///初始化语言的选择器
          spinngerAdapter=SpinngerAdapter.getSpinngerAdapter()
                .context(this)
                .dropdown_item(R.layout.spirng)
                .listData(language)
                .spinner(activitysMainBinding.spinnerLanguage)
                .onCallAdapter(this);
          spinngerAdapter.getArrayAdapter();

        for (int i=0;i<allLanguage.size();i++){
                    String it=allLanguage.get(i).getLanguageCode();
                    translation_language.add(it);
        }


        if (!translation_language.contains(languageTypeBean.getData().getTeacherLanguage().getLinkCode())){
            translation_language.add(0,languageTypeBean.getData().getTeacherLanguage().getLinkCode());
        }

        System.out.println(languageName+"-------"+translation_language);

        ///初始化语言和翻译语言
        speechTransUtils=SpeechTransUtils.getSpeechTransUtils()
                .setLanguage(languageName)
                .setTranslationLanguage(translation_language)
                .key(AppConstants.getSpeechSubscriptionKey(),AppConstants.getServiceRegions());
        speechTransUtils.initialize();

        languageCodes=languageDataBeans.getLanguageCode();
        ///模拟测试数据
//        mainTeachingBean= moni();
//
    }



    private  MainAdapter myAdapter;

    ///初始化列表
    private void initRe(String username) {
        LinearLayoutManager gridLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        activitysMainBinding.display.setLayoutManager(gridLayoutManager);
        myAdapter = new MainAdapter(this, mianReBeans,username);
        activitysMainBinding.display.setAdapter(myAdapter);
    }

    private List<PdfurlBean>  pdfurlBeans=new LinkedList<>();
    ///过滤出学生的语言并下载对一个语言的文件
    int  pdfurlBeansstate=1;
    String screenLanguageCode="";
    private void  filterfile(MainTeachingBean mainTeachingBean,String LanguageCode){
        pdf_url="";
        if (pdfurlBeans.size()>0){
            pdfurlBeans.clear();
        }
        for (int i=0;i<mainTeachingBean.getData().getStuCourseFiles().size();i++){
            MainTeachingBean.DataBean.StuCourseFilesBean stuCourseFilesBean= mainTeachingBean.getData().getStuCourseFiles().get(i);
            if(stuCourseFilesBean.getLanguageCode().equals(LanguageCode)){
                pdfurlBeans.add(new PdfurlBean(stuCourseFilesBean.getUrl(),stuCourseFilesBean.getLanguageCode(),stuCourseFilesBean.getDocName()));
            }
        }
        if (pdfurlBeans.size()>1){
            for (int i=0;i<pdfurlBeans.size();i++){
                 if (pdfurlBeans.get(i).getDocNames().equals(docName)){
                     //System.out.println("JWebSocketClientService执行了课件11111"+pdfurlBeans.get(i).getUrl()+"-------"+pdfurlBeans.get(i).getDocNames());
                     pdf_url=pdfurlBeans.get(i).getUrl();
                     langCode=pdfurlBeans.get(i).getLangCode();
                     docNames=pdfurlBeans.get(i).getDocNames();
                     pdfurlBeansstate=2;

                 }
            }

            if (pdfurlBeansstate==1){
                ToastUtil.showToast("No corresponding courseware found");
                DemoApplication.getHandlerUtils().saveCrashInfo2File("下载地址No corresponding courseware found");
            }
            pdfurlBeansstate=1;
        }else {
            if (pdfurlBeans.get(0).getDocNames().equals(docName)){
                pdf_url=pdfurlBeans.get(0).getUrl();
                langCode=  pdfurlBeans.get(0).getLangCode();
                docNames=  pdfurlBeans.get(0).getDocNames();
            }else{
                ToastUtil.showToast("No corresponding courseware found");
                DemoApplication.getHandlerUtils().saveCrashInfo2File("下载地址No corresponding courseware found");
            }
        }

        if (pdf_url.equals("")){
            DemoApplication.getHandlerUtils().saveCrashInfo2File("下载地址null");
            if (activitysMainBinding.liRoot.getChildCount()>0){
                activitysMainBinding.liRoot.removeAllViews();
            }
            System.out.println("JWebSocketClientService执行了课件11111");
            return;
        }
        DemoApplication.getHandlerUtils().saveCrashInfo2File("下载地址"+"----"+pdf_url);
        System.out.println("JWebSocketClientService执行了课件11111执行了"+pdf_url);
        if (!docNamess.equals(docNames) || !screenLanguageCode.equals(LanguageCode) ){
            docNamess=docNames;
            screenLanguageCode=LanguageCode;
            downLoads(langCode);
        }else {
            b.putInt("progress", curPageIndex);
            TbsFileInterfaceImpl.getInstance().gotoPosition(b);
        }

    }


    private void downLoads(String fileName){
        officeSaveName=fileName+"."+FileUtil.getFileType(pdf_url);
        String path= FileUtil.getCachePath(MainActivitys.this);
        File file=new File(path,officeSaveName);
        downloadUtil= DownloadUtil.get();
        downLoadFile();
    }


    ///下载服务器的文件
    private void downLoad(String fileName){
        officeSaveName=fileName+"."+FileUtil.getFileType(pdf_url);
        if(tbsReaderView!=null){
            tbsReaderView.onStop();
        }
        tbsReaderView = new TbsReaderView(this, this);
        String path= FileUtil.getCachePath(MainActivitys.this);
        File file=new File(path,officeSaveName);
        downloadUtil= DownloadUtil.get();
        downLoadFile();
    }



    private CodeBean codeBean=new CodeBean();
    private   MainTeachingBean moni(){
//        List<CodeBean.DataBean.CourseFileUrlBean> courseFileUrlBeans=new LinkedList<>();
//        List<CodeBean.DataBean.SpeechFileUrlBean> speechFileUrlBeans=new LinkedList<>();
//        CodeBean.DataBean.CourseFileUrlBean courseFileUrlBean=new CodeBean.DataBean.CourseFileUrlBean();
//        courseFileUrlBean.setLanguageCode("en");
//        courseFileUrlBean.setUrl("https://uat.metalingual.com.cn/upload/doc/1784474593264459778/1784474597249048577.docx");
//        CodeBean.DataBean.CourseFileUrlBean courseFileUrlBeanOne=new CodeBean.DataBean.CourseFileUrlBean();
//        courseFileUrlBeanOne.setLanguageCode("zh");
//        courseFileUrlBeanOne.setUrl("https://uat.metalingual.com.cn/upload/doc/1784474593264459778/1784474600000512002.docx");
//        CodeBean.DataBean.CourseFileUrlBean courseFileUrlBeanTwo=new CodeBean.DataBean.CourseFileUrlBean();
//        courseFileUrlBeanTwo.setLanguageCode("zh");
//        courseFileUrlBeanTwo.setUrl("https://uat.metalingual.com.cn/upload/doc/1784474593264459778/1784474593272848385.docx");
//
//
//        courseFileUrlBeans.add(courseFileUrlBean);
//        courseFileUrlBeans.add(courseFileUrlBeanOne);
//        courseFileUrlBeans.add(courseFileUrlBeanTwo);
//
//
//        CodeBean.DataBean.SpeechFileUrlBean speechFileUrlBean=new CodeBean.DataBean.SpeechFileUrlBean();
//        speechFileUrlBean.setLanguageCode("en");
//        speechFileUrlBean.setUrl("https://uat.metalingual.com.cn/upload/doc/1784474593264459778/1784474597249048577.docx");
//        CodeBean.DataBean.SpeechFileUrlBean speechFileUrlBeanOne=new CodeBean.DataBean.SpeechFileUrlBean();
//        speechFileUrlBeanOne.setLanguageCode("zh");
//        courseFileUrlBeanOne.setUrl("https://uat.metalingual.com.cn/upload/doc/1784474593264459778/1784474600000512002.docx");
//        CodeBean.DataBean.SpeechFileUrlBean speechFileUrlBeanTwo=new CodeBean.DataBean.SpeechFileUrlBean();
//        speechFileUrlBeanTwo.setLanguageCode("zhs");
//        courseFileUrlBeanTwo.setUrl("https://uat.metalingual.com.cn/upload/doc/1784474593264459778/1784474593272848385.docx");
//
//        speechFileUrlBeans.add(speechFileUrlBean);
//        speechFileUrlBeans.add(speechFileUrlBeanOne);
//        speechFileUrlBeans.add(speechFileUrlBeanTwo);
//
//        CodeBean.DataBean co=new CodeBean.DataBean();
//        co.setSpeechFileUrl(speechFileUrlBeans);
//        co.setCourseFileUrl(courseFileUrlBeans);
//        codeBean.setData(co);
//        codeBean.setCmd("ssdsd");
//        codeBean.setTime("2020-11-07");
//        Intent intent1=new Intent(MainActivitys.this,CodeActivity.class);
//        intent1.putExtra("Url",GsonUtil.GsonString(codeBean));
//        intent1.putExtra("code",languageCodes);
//        startActivity(intent1);
//        finish();

//        Intent intent1=new Intent(MainActivitys.this,CodeActivity.class);
//        intent1.putExtra("Url","{\"Cmd\":\"FinalTeaching\",\"Data\":{\"CourseFileUrl\":[],\"SpeechFileUrl\":null},\"Time\":\"2024-05-14 09:38:42\"}");
//        intent1.putExtra("code",languageCodes);
//        startActivity(intent1);
//        finish();

//
        MainTeachingBean  mainTeachingBean=new MainTeachingBean();
        MainTeachingBean.DataBean dataBean=new MainTeachingBean.DataBean();
        List<MainTeachingBean.DataBean.StuCourseFilesBean> stuCourseFilesBeans=new LinkedList<>();
        MainTeachingBean.DataBean.StuCourseFilesBean m=new MainTeachingBean.DataBean.StuCourseFilesBean();
        m.setLanguageCode("en");
        m.setLanguageName("英语（英国）");
        m.setLanguageEnName("English (United Kingdom)");
        m.setDocName("《多语种智慧教室》PC与安卓数据交互接口文档3.0_英语（英国）.docx");
        m.setUrl("https://uat.metalingual.com.cn/upload/doc/1792781330534985730/1792781330539180033.txt");
        stuCourseFilesBeans.add(m);
        MainTeachingBean.DataBean.StuCourseFilesBean m1=new MainTeachingBean.DataBean.StuCourseFilesBean();
        m1.setLanguageCode("ja");
        m1.setLanguageName("日语（日本）");
        m1.setLanguageEnName("Japanese (Japan)");
        m1.setDocName("《多语种智慧教室》PC与安卓数据交互接口文档3.0_日语（日本）.docx");
        m1.setUrl("https://uat.metalingual.com.cn/upload/doc/1783333973128908801/1783333984172511234.docx");
        stuCourseFilesBeans.add(m1);

        dataBean.setStuCourseFiles(stuCourseFilesBeans);
        mainTeachingBean.setData(dataBean);
        return  mainTeachingBean;

    }
    //                     }else {
//                         b.putInt("progress", curPageIndex);
//                         TbsFileInterfaceImpl.getInstance().gotoPosition(b);
//                     }
    private String docName="";
    private String docNamess="";

    /**
     * SPP蓝牙连接广播监听
     */
    String time="";
    String stop="";
    int page;
    PageInfoBean pageInfoBean;
    int s=0;
    boolean isState=false;
    private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
        //@RequiresApi(api = Build.VERSION_CODES.P)
        @Override
        public void onReceive(Context context, final Intent intent) {
            action = intent.getAction();
            String message = intent.getStringExtra("message");
            // WebSocket收到数据
            if (action.equals(AppConstants.WEBSOCKET_TEACHING_ACTION)) {//PC主动推送开始授课信号
                  Log.i("JWebSocketClientService", "message开始授课:" + message);
                   mainTeachingBean=GsonUtil.GsonToBean(message, MainTeachingBean.class);
                   if(!mainTeachingBean.getTime().equals(time)){
                       time=mainTeachingBean.getTime();
//                       languageCodes=languageDataBeans.getLanguageCode();
//                       if (mainTeachingBean.getData().getStuCourseFiles().size()>0){
//                           filterfile(mainTeachingBean,languageCodes);
//                       }
//
//                       if(mainTeachingBean.getData().getStuCourseFiles().size()<=0){
//                         activitysMainBinding.kejian.setVisibility(View.GONE);
//                       }
                   }
                stop="1";
            }else  if (action.equals(AppConstants.WEBSOCKET_STOP_TEACHING_ACTION)){//PC主动推送暂停授课信号
                 Log.i("JWebSocketClientService", "message:暂停授课" + message);
                 MainPauseTeachingBean mainPauseTeachingBean=GsonUtil.GsonToBean(message, MainPauseTeachingBean.class);
                 if(!mainPauseTeachingBean.getTime().equals(time)){
                     time=mainPauseTeachingBean.getTime();
                 }
                stop="";
                DemoApplication.getHandlerUtils().saveCrashInfo2File("暂停授课"+"-----"+stop);
            }else  if (action.equals(AppConstants.WEBSOCKET_COLSE_TEACHING_ACTION)){//PC主动推送结束授课信号
                    Pref.put(AppConstants.languageCodess,languageCodes);
                    SelectLanguageActivitys.activitys.stopcourse();
                    Log.i("JWebSocketClientService", "message:结束授课" + message);
                    Intent intent1=new Intent(MainActivitys.this,CodeActivity.class);
                    intent1.putExtra("Url",message);
                    intent1.putExtra("te",teacher_curriculum);
                    intent1.putExtra("code",languageCodes);
                    intent1.putExtra("yuan",languageName);
                    startActivity(intent1);
                    finish();

            }else  if (action.equals(AppConstants.WEBSOCKET_LIVESPEECH_TEACHING_ACTION)){//PC端主动推送教师发言内容: PC(教师端) → Android(学生端)
                MainStudentBean mainStudentBean=GsonUtil.GsonToBean(message, MainStudentBean.class);

                //Log.i("zzg", "message:教师发言" + languageTypeBean.getData().getSessionId()+"-------"+mainStudentBean.getData().get(0).getSessionId());
                  if (mainStudentBean.getData().size()>0){
                      if (languageTypeBean.getData().getSessionId().equals(mainStudentBean.getData().get(0).getSessionId())){
                          if(!mainStudentBean.getTime().equals(time)){
                              time=mainStudentBean.getTime();
                              for(int i=0;i<mainStudentBean.getData().size();i++){
                                  if(mainStudentBean.getData().get(i).getLanguageCode().equals(languageCodes)){
                                      mianReBeans.add(new MianReBean(mainStudentBean.getTime(),languageTypeBean.getData().getTeacher(),mainStudentBean.getData().get(i).getContent(),"1"));
                                  }
                              }

                              myAdapter.setmData(mianReBeans);
                              myAdapter.notifyDataSetChanged();
                              if (mianReBeans.size()>4){
                                  activitysMainBinding.display.smoothScrollToPosition(mianReBeans.size()-1);
                              }

                          }
                      }else{
                          Log.i("JWebSocketClientService", "message:教师发言获取到sssssss");
                          for(int i=0;i<mainStudentBean.getData().size();i++){
                              if(mainStudentBean.getData().get(i).getLanguageCode().equals(languageCodes)){
                                  mianReBeans.add(new MianReBean(mainStudentBean.getTime(),mainStudentBean.getData().get(i).getSpeeker(),mainStudentBean.getData().get(i).getContent(),"1"));
                              }
                          }
                          myAdapter.setmData(mianReBeans);
                          myAdapter.notifyDataSetChanged();
                          if (mianReBeans.size()>4){
                              activitysMainBinding.display.smoothScrollToPosition(mianReBeans.size()-1);
                          }
                      }
                  }

            }else  if (action.equals(AppConstants.WEBSOCKET_SY_TEACHING_ACTION)){//PC端主动推送教师课件页码: PC(教师端) → Android(学生端)
                Log.i("JWebSocketClientService", "message:教师页码" + message);
                pageInfoBean=GsonUtil.GsonToBean(message,PageInfoBean.class);
                if (pageInfoBean!=null){
                     if (pageInfoBean.getData()!=null){
                         docName=pageInfoBean.getData().getFileName();
                         curPageIndex=pageInfoBean.getData().getPageNum();
                         Log.i("JWebSocketClientService", "message:教师页码" + docName);
                         kejian();
                     }else{
                         activitysMainBinding.kejian.setVisibility(View.GONE);
                     }
                }else {
                    activitysMainBinding.kejian.setVisibility(View.GONE);
                }

            }else  if(action.equals(AppConstants.colse)){//连接断开后退出页面重新连接
                colse();
                finish();
                SelectLanguageActivitys.activitys.start();
            }else  if (action.equals(AppConstants.WEBSOCKET_SNED_MESSAGE_ACTION)){
                Log.i("JWebSocketClientService", "message:教师推送语种" + message);
                Intent intent1=new Intent(MainActivitys.this,LoginActivity.class);
                intent1.putExtra("message",message);
                startActivity(intent1);
                finish();
            }else  if (action.equals(AppConstants.WEBSOCKET_SY_LANGUAGE_SPEEHING)){//PC↔安卓讲话中实时翻译推送
                Log.i("JWebSocketClientService", "message:是否有人说话" + message);
                MainStudentBean mainStudentBean=GsonUtil.GsonToBean(message, MainStudentBean.class);
                showtext(mainStudentBean);
            }else  if (action.equals(AppConstants.WEBSOCKET_SY_LANGUAGE_ResponseSpeech)){//PC 回复安卓是否发言
//                Log.i("JWebSocketClientService", "message:是否有人说话" + message);
                ResponseSpeechBean responseSpeechBean =GsonUtil.GsonToBean(message,ResponseSpeechBean.class);
                isState =responseSpeechBean.getData().isCanSpeech();
                if (isState && reState==1 && uuid.equals(responseSpeechBean.getData().getUUID())){
                    Log.i("JWebSocketClientService", "执"+reState);
                    DemoApplication.getHandlerUtils().saveCrashInfo2File("ResponseSpeech执行一次"+"-----"+reState);
                    reState++;
                    down();
                }else if (isState && reState==1 && !uuid.equals(responseSpeechBean.getData().getUUID())){
//                    ToastUtil.showToast("The current network is abnormal or slow");
                    Log.i("JWebSocketClientService", "执行了几次"+reState);
                    DemoApplication.getHandlerUtils().saveCrashInfo2File("ResponseSpeech多次"+"-----"+reState);
                }else if (isState && reState==2){
//                    ToastUtil.showToast("The current network is abnormal or slow");
                    Log.i("JWebSocketClientService", "执行了几次"+reState);
                    DemoApplication.getHandlerUtils().saveCrashInfo2File("ResponseSpeech多次"+"-----"+reState);
                } else {
                    ToastUtil.showToast("Someone is speaking");
                }
            }else if (action.equals(AppConstants.WEBSOCKET_SY_LANGUAGE_StudentSpeeching)){///获取其他同学说话的数据
                Log.i("JWebSocketClientService", "message:学生说话" + message);
                MainStudentBean mainStudentBean=GsonUtil.GsonToBean(message, MainStudentBean.class);
                showtext(mainStudentBean);
            }

        }
    };


    void  showtext(MainStudentBean mainStudentBean){
        if (mainStudentBean!=null){
            if (mainStudentBean.getData()!=null){
                if (mainStudentBean.getData().size()>0){
                    for (int i=0;i<mainStudentBean.getData().size();i++){
                        s=i;
                        if (mainStudentBean.getData().get(i).getLanguageCode().equals(languageCodes)){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    activitysMainBinding.studenttext.setText(mainStudentBean.getData().get(s).getSpeeker()+":");
                                    activitysMainBinding.studentmessage.setText(mainStudentBean.getData().get(s).getContent());
                                }
                            });
                        }
                    }
                }
            }
        }
    }


    void  kejian(){
        if (mainTeachingBean==null){
            activitysMainBinding.kejian.setVisibility(View.GONE);
            return;
        }
        if (mainTeachingBean.getData()==null){
            activitysMainBinding.kejian.setVisibility(View.GONE);
            return;
        }else  if (mainTeachingBean.getData().getStuCourseFiles()==null){
            activitysMainBinding.kejian.setVisibility(View.GONE);
            return;
        }


        if (mainTeachingBean.getData().getStuCourseFiles().size()>0){
            System.out.println("JWebSocketClientService执行了课件");
            activitysMainBinding.kejian.setVisibility(View.VISIBLE);
            filterfile(mainTeachingBean,languageCodes);
        }

        if(mainTeachingBean.getData().getStuCourseFiles().size()<=0){
            activitysMainBinding.kejian.setVisibility(View.GONE);
        }
    }


    /**
     * 初始化WebSocket服务
     */
    private void initWebSocket() {
        System.out.println("启动了服务");
        IntentFilter discoveryFilter = new IntentFilter();
        discoveryFilter.addAction(AppConstants.WEBSOCKET_TEACHING_ACTION);
        discoveryFilter.addAction(AppConstants.WEBSOCKET_STOP_TEACHING_ACTION);
        discoveryFilter.addAction(AppConstants.WEBSOCKET_COLSE_TEACHING_ACTION);
        discoveryFilter.addAction(AppConstants.WEBSOCKET_LIVESPEECH_TEACHING_ACTION);
        discoveryFilter.addAction(AppConstants.WEBSOCKET_SNED_MESSAGE_ACTION);
        discoveryFilter.addAction(AppConstants.WEBSOCKET_SY_TEACHING_ACTION);
        discoveryFilter.addAction(AppConstants.colse);
        discoveryFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        discoveryFilter.addAction(AppConstants.WEBSOCKET_SY_LANGUAGE_SPEEHING);
        discoveryFilter.addAction(AppConstants.WEBSOCKET_SY_LANGUAGE_ResponseSpeech);
        discoveryFilter.addAction(AppConstants.WEBSOCKET_SY_LANGUAGE_StudentSpeeching);

        registerReceiver(mBluetoothReceiver, discoveryFilter);
        Servicess.getService().getjWebSClientService().sendMsg("{\"Cmd\":\"JoinClassroom\",\"Data\":{}}", new JWebSocketClientService.OnCallBack() {
            @Override
            public void onSend(String state) {

            }
        });
    }






    /**
     * 下载文件
     */

    FileVo  fileVo=new FileVo();
    private  void   downLoadFile(){
        Observable.create(new ObservableOnSubscribe<FileVo>() {
            @Override
            public void subscribe(final ObservableEmitter<FileVo> e) throws Exception {

                String path= FileUtil.getCachePath(MainActivitys.this);

                downloadUtil.download(pdf_url, path,
                        officeSaveName,
                        new DownloadUtil.OnDownloadListener() {
                            @Override
                            public void onDownloadSuccess(File file) {
                                fileVo.setFile(file);
                                e.onNext(fileVo);
                                e.onComplete();
                            }
                            @Override
                            public void onDownloading(int progress) {
                                Log.d("当前下载的进度",""+progress);
                                showProgress(progress);
                            }
                            @Override
                            public void onDownloadFailed(Exception e) {
                            }
                        });
            }

        }).compose(RxUtils.schedulersTransformer()).subscribe(new Consumer<FileVo>() {
            @Override
            public void accept(FileVo fileVo) {
                showOffice(fileVo);
            }
        });
    }


    /**
     * 加载文件
     */
    private   void   showOffice(FileVo fileVo){
        activitysMainBinding.numberProgressBar.setProgress(fileVo.getProgress());
        file=fileVo.getFile();
        if (DemoApplication.getIson()){
            openFile(file.toString());
        }else {
            ToastUtil.showToast("Engine initialization failed");
        }

//        String bsReaderTemp = tbsReaderTemp;
//        File bsReaderTempFile =new File(bsReaderTemp);
//        if (!bsReaderTempFile.exists()) {
//            boolean mkdir = bsReaderTempFile.mkdir();
//            if(!mkdir){
//                Log.d("print","创建/TbsReaderTemp失败！！！！！");
//            }
//        }
//        //加载文件
//        Bundle localBundle = new Bundle();
//        localBundle.putString("filePath", file.toString());
//        localBundle.putString("tempPath", tbsReaderTemp);
//        if (tbsReaderView == null){
//            tbsReaderView = getTbsView();
//        }
//
//        boolean result = tbsReaderView.preOpen(FileUtil.getFileType(file.toString()), false);
//        if (result) {
//              tbsReaderView.openFile(localBundle);
//        }else{
//            DemoApplication.getHandlerUtils().saveCrashInfo2File("打开失败");
//        }
//        activitysMainBinding.liRoot.removeAllViews();
//        activitysMainBinding.liRoot.addView(tbsReaderView);
    }


    /**
     * 显示进度
     * @param progress
     */
    private   void   showProgress(final int  progress){
        Observable.just(progress)
                .compose(RxUtils.schedulersTransformer())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        activitysMainBinding.numberProgressBar.setProgress(progress);
                    }
         });

    }



    private   TbsReaderView  getTbsView(){
        return  new TbsReaderView(MainActivitys.this,this);
    }


    @Override
    public void onCallBackAction(Integer integer, Object o, Object o1) {

//       System.out.println(integer+"获取数据");
//       System.out.println(o+"获取数据");
//       System.out.println(o1+"获取数据");
    }

    String languageName,languageCodes;
    @Override
    public void adapter(AdapterView<?> parent, View view, int position, long id) {
           if (state==0){
               state=1;
               return;
           }
//           if(mainTeachingBean==null){
//             ToastUtil.showToast("开始授课失败");
//             return;
//           }

           languageName=language.get(position).getLinkCode();
           languageCodes=language.get(position).getLanguageCode();
           System.out.println(languageName+"后去数据"+languageCodes);
           speechTransUtils.setLanguage(languageName);

           //有课件
            if(mainTeachingBean!=null){
                if (mainTeachingBean.getData().getStuCourseFiles().size()>0){
                    if (pageInfoBean!=null){
                        if (pageInfoBean.getData()!=null){
                            activitysMainBinding.kejian.setVisibility(View.VISIBLE);
                            filterfile(mainTeachingBean,languageCodes);
                        }else {
                            activitysMainBinding.kejian.setVisibility(View.GONE);
                        }
                    }else {
                        activitysMainBinding.kejian.setVisibility(View.GONE);
                    }
                }else {
                    activitysMainBinding.kejian.setVisibility(View.GONE);
                }
            }else {
                activitysMainBinding.kejian.setVisibility(View.GONE);
            }


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//        Log.e("MainTestActivity", "执行销毁");
          isDestroyed=false;
          destroy();
          stopTask();
          colse();
    }

    void  colse(){
          unregisterReceiver(mBluetoothReceiver);
          if (tbsReaderView!=null){
             tbsReaderView.onStop();
          }
    }

    MainStudentBean mainStudentBean=new MainStudentBean();
    List<MainStudentBean.DataBean> dataBeans=new LinkedList<>();
    List<MainStudentBean.DataBean> dataBeanss=new LinkedList<>();
    int Duration=0;


    CompositeDisposable disposables = new CompositeDisposable();

    // 开始或重新开始任务
    void startTask() {
        disposables.add(Observable.interval(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    seconds++;
                    System.out.println("JWebSocketClientService定时数据"+seconds);
                    if (seconds==8){
                        seconds=0;
                        stopTask();
                        System.out.println("JWebSocketClientService定时关闭");
                    }
                    // 这里是你想要反复执行的代码
                })); // 打印错误
    }


    // 开始或重新开始任务
    void startTasks() {
        disposables.add(Observable.interval(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    System.out.println("定时数据1");
                    activitysMainBinding.scrool.fullScroll(ScrollView.FOCUS_DOWN);
                    Duration++;
                    Log.i("wangbaoxuan", Duration+"");


                    // 这里是你想要反复执行的代码
                })); // 打印错误
    }

    // 停止任务
    void stopTask() {
        disposables.clear(); // 清空所有订阅，停止任务
    }


    int states=1;
    int index=0;
    String times="";
    String recognizingString="" ,recognizedString="";
    int recognizingState=1;

    public  String generateUniqueSequence() {
        return UUID.randomUUID().toString();
    }


    String uuid="";
    int seconds=0;//控制按下时间
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN://按下
                uuid=generateUniqueSequence();
                reState=1;
                DemoApplication.getHandlerUtils().saveCrashInfo2File("点击MainActivitys按下语言按钮"+"-----"+stop+"uuid------"+uuid+"更新了");
                if (seconds==0){
                    seconds++;
                    controlPress();
                }else {
                    ToastUtil.showToast("Please click the button to speak in 10 seconds");
                }
                break;
            case MotionEvent.ACTION_UP://抬起
                System.out.println("JWebSocketClientService执行了按下");
                reState=2;
                DemoApplication.getHandlerUtils().saveCrashInfo2File("点击MainActivitys松开语言按钮"+"-----"+stop+"更新了");
                if(stop.equals("1")){
                    onSend("{\"Cmd\":\"SpeechFinished\",\"Data\":{}}");
                    SpeechTransUtils.getSpeechTransUtils().stopSpeech();
                    stopTask();
                    activitysMainBinding.buttons.setText("Long press speak");
                }
                startTask();
                break;

        }
        return true;
    }


    void controlPress(){
        if(stop.equals("1")){
            SpeechTransUtils.getSpeechTransUtils().stop();
            onSend("{\"Cmd\":\"RequestSpeech\",\"Data\":\""+uuid+"\"}");
        }else {
            ToastUtil.showToast("Unable to speak during course pause");
        }
    }

    void down(){
        if(stop.equals("1")){
//            stringBuilder=new StringBuilder();
//            stringBuilders=new StringBuilder();
            recognizingState=1;
            activitysMainBinding.studentmessage.setText("");
            recognizingString="";
            recognizedString="";
            states=0;
            times="";
            //启动定时器
            startTasks();
            activitysMainBinding.studenttext.setText(username+":");
            activitysMainBinding.buttons.setText("Currently in progress speak");
            SpeechTransUtils.getSpeechTransUtils().startSpeech(new SpeechTransUtils.SpeechCallBack() {
                @Override
                public void value(String languages, String translation_languages,String key) {
                    String languageCode="";
                    ///添加多个列表
                    if (Duration==0){
                        Duration=1;
                    }
                    Log.i("xianshi", dataBeans.size()+"-------"+translation_language.size());
                    if (languageCodes.equals(key)){
                        dataBeans.add(new MainStudentBean.DataBean(
                                        activitysMainBinding.student.getText().toString(),
                                        key,
                                        translation_languages,
                                        Duration,
                                        true,
                                        hashCode
                                )
                        );
                        recognizedString=translation_languages;
                    } else {
                        dataBeans.add(new MainStudentBean.DataBean(
                                        activitysMainBinding.student.getText().toString(),
                                        key,
                                        translation_languages,
                                        Duration,
                                        false,
                                        hashCode
                                )
                        );
                    }
                    if(dataBeans.size()==translation_language.size()){
                        fasong(recognizedString);
                        Log.i("wangbaoxuanssssss", "wangbaoxuan:"+Duration);
//                      for (int i=0;i<dataBeans.size();i++){
//                            if (dataBeans.get(i).getLanguageCode().equals(key)){
//                                String s= dataBeans.get(i).getContent();
//                                String newString=s+translation_languages;
//                                dataBeans.get(i).setContent(newString);
//                                dataBeans.get(i).setDuration(Duration);
//                            }
//                       }
//                    }else {
                        Log.i("xianshi", "wangbaoxuan:"+languageCodes+"-------"+key+"-----"+Duration);

                    }

                }

                @Override
                public void valuerecognizing(String language, String translation_languagess, String key) {
                    if(dataBeanss.size()==translation_language.size()){
                        Log.i("JWebSocketClientService", "message:实时"+ GsonUtil.GsonString(mainStudentBean));
                        dataBeanss.clear();
                     }
                    System.out.println(translation_language+"------"+key+"----"+language);
                        dataBeanss.add(new MainStudentBean.DataBean(
                                activitysMainBinding.student.getText().toString(),
                                key,
                                translation_languagess,
                                hashCode
                        ));

                        mainStudentBean.setCmd("StudentSpeeching");
                        mainStudentBean.setData(dataBeanss);
                        onSend(GsonUtil.GsonString(mainStudentBean));
                 }

                @Override
                public void recognizing(String language) {
//                      recognizingState=1;
                    recognizingString=language;
//                    stringBuilders.append(language);
                    Log.i("sss", "languageDataBean:"+language);
                    runOnUiThread(new Runnable(){
                        @Override
                        public void run() {
                            //更新UI
                            activitysMainBinding.studentmessage.setText(recognizingString);
                        }
                    });
                }

                @Override
                public void recognized(String language) {

//                    stringBuilder.append(language);
//                    recognizingState=2;
                    Log.i("wangbaoxuanssss", "languageDataBean:"+recognizingState);
                }

            });
        }else {
            ToastUtil.showToast("Unable to speak during course pause");
        }
    }



    void  fasong(String name){
//           if(recognizingState==2){

//                activitysMainBinding.studentmessage.setText(stringBuilder.toString());
                if (dataBeans.size()<=0){
                    activitysMainBinding.buttons.setText("Long press speak");
                    Duration = 0;
                    SpeechTransUtils.getSpeechTransUtils().stopSpeech();
                    return;
                }else {
                        for (int i=0; i<dataBeans.size();i++){
                            dataBeans.get(i).setDuration(Duration);
                        }
//                        for (int i=0;i<dataBeans.size();i++){//统一下目标语言
//                             if (dataBeans.get(i).getLanguageCode().equals(languageCodes)){
//                                 dataBeans.get(i).setContent(name);
//                             }
//                        }
                }


                mainStudentBean.setCmd("LiveSpeech");
                mainStudentBean.setData(dataBeans);
                if (mainStudentBean.getTime()==null){
                    mainStudentBean.setTime(time());
                    //MianReBean mianReBean = new MianReBean(mainStudentBean.getTime(),  activitysMainBinding.student.getText().toString(),stringBuilder.toString(),"1");
                    MianReBean mianReBean = new MianReBean("",  activitysMainBinding.student.getText().toString(),name,"1");
                    mianReBeans.add(mianReBean);
                }else {
                    Calendar pastTime = Calendar.getInstance(); // 假设这是过去的某个时间
                    pastTime.setTime(date);
                    boolean isPastFive = isPastFiveMinutes(pastTime);
                    if(isPastFive){
                        System.out.println("超过5分钟");
                        MianReBean mianReBean = new MianReBean("",  activitysMainBinding.student.getText().toString(),name,"1");
                        //MianReBean mianReBean = new MianReBean(time(),  activitysMainBinding.student.getText().toString(),stringBuilder.toString(),"1");
                        mianReBeans.add(mianReBean);
                    }else {
                        System.out.println("没超5两分钟");
                        MianReBean mianReBean = new MianReBean("",  activitysMainBinding.student.getText().toString(),name,"1");
                      //MianReBean mianReBean = new MianReBean(mainStudentBean.getTime(),  activitysMainBinding.student.getText().toString(),stringBuilder.toString(),"2");
                        mianReBeans.add(mianReBean);
                    }
                }
                Log.i("wangbaoxuan", "wangbaoxuan:" + recognizingString);
                Log.i("wangbaoxuan", "wangbaoxuan:" + GsonUtil.GsonString(dataBeans));
                Log.i("wangbaoxuan", "wangbaoxuan:" + GsonUtil.GsonString(mainStudentBean));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //更新UI
                        myAdapter.notifyDataSetChanged();
                        if (mianReBeans.size() > 4) {
                            activitysMainBinding.display.smoothScrollToPosition(mianReBeans.size() - 1);
                        }
                    }
                });
                boolean cstates=  onSend(GsonUtil.GsonString(mainStudentBean));
                if (cstates){
                    ToastUtil.showToast(MainActivitys.this,"Connection exception");
                }
                Duration = 0;
                if (dataBeans.size() > 0) {
                    dataBeans.clear();
                }

//           }
    }

    boolean  onSend(String value){
       boolean state= Servicess.getService().getjWebSClientService().sendMsg(value, new JWebSocketClientService.OnCallBack() {
            @Override
            public void onSend(String state) {
                if(state=="2"){
//                  onSend(GsonUtil.GsonString(mainStudentBean));
                }else {
//                    ToastUtil.showToast(MainActivitys.this,"Sending successful");
                }
            }
        });
        return state;
    }




    ///获取上传时间
    Date date;
    private String time(){
        date=new Date(System.currentTimeMillis());
        SimpleDateFormat formatter = new SimpleDateFormat("MM-dd HH:mm"); //设置时间格式
        String createDate = formatter.format(date);   //格式转换
        return  createDate;
    }

    public boolean isPastFiveMinutes(Calendar pastTime) {
        Calendar now = Calendar.getInstance();
        // 假设过去的时间是参数传入的
        // 计算过去时间与当前时间的差
        long diff = now.getTimeInMillis() - pastTime.getTimeInMillis();
        // 将毫秒转换为分钟，并检查是否超过5分钟
        return diff > 5 * 60 * 1000;
    }


    @Override
    public void onBackPressed() {
        // 禁用返回键，不执行任何操作
    }
//        // 上一页
//        Bundle b = new Bundle();
//        b.putInt("progress", curPageIndex - 1);
//        TbsFileInterfaceImpl.getInstance().gotoPosition(b); // 传入页面对应的数组下标
//      下一页
//      Bundle b = new Bundle();
//      b.putInt("progress", curPageIndex + 1);
//      TbsFileInterfaceImpl.getInstance().gotoPosition(b);


    private boolean isDestroyed = false;
    private int curPageIndex = -1;
    private int page_count=0;
    private void openFile(String  file) {
        //设置回调
        ITbsReaderCallback callback = new ITbsReaderCallback() {
            @Override
            public void onCallBackAction(Integer actionType, Object args, Object result) {
                Log.i("LocaActivity", "actionType=" + actionType + "，args=" + args + "，result=" + result);
                if (ITbsReader.OPEN_FILEREADER_STATUS_UI_CALLBACK == actionType) {
                    if (args instanceof Bundle) {
                        int id = ((Bundle) args).getInt("typeId");
                        if (ITbsReader.TBS_READER_TYPE_STATUS_UI_SHUTDOWN == id) {
                            finish();       // 加密文档弹框取消需关闭activity
                        }
                    }
                }else if (ITbsReader.READER_PAGE_TOAST == actionType) {
                    // cur_page获取到的是当前真实的页码，需要-1才能得到页面对应的数组下标
//                    curPageIndex = ((Bundle) args).getInt("cur_page") - 1;
                    page_count= ((Bundle) args).getInt("page_count") ;
                    System.out.println("获取数据"+curPageIndex+"------"+page_count);
                }else  if (ITbsReader.NOTIFY_CANDISPLAY == actionType){
                    System.out.println("获取数据sssssssss");
                    b.putInt("progress", curPageIndex);
                    TbsFileInterfaceImpl.getInstance().gotoPosition(b);
                }
            }
        };
        String [] s= file.split("/");
        String txts=s[s.length-1];
        isDestroyed=false;
        destroy();
//        System.out.println(txts+"获取数据");
        String[] ss= txts.split("\\.");
//        System.out.println(ss[1]+"获取数据");
        //设置参数
        Bundle param = new Bundle();
        param.putString("filePath", file);
        param.putString("fileExt", ss[1]); // 文件后缀名，如文件名为test.pdf，则只需要传入"pdf"
        param.putString("tempPath", getExternalFilesDir("temp").getAbsolutePath());
        //调用openFileReader打开文件
        activitysMainBinding.liRoot.post(new Runnable() {
            @Override
            public void run() {
                int height = activitysMainBinding.liRoot.getHeight();
                // 自定义layout模式必须设置这个值，否则可能导致文档内容显示不全
                param.putInt("set_content_view_height", height);
                int ret = TbsFileInterfaceImpl.getInstance().openFileReader(
                        MainActivitys.this, param, callback, activitysMainBinding.liRoot);
            }
        });
    }


    // 销毁资源使用onpause + ondestroy的方式。避免onDestroy延迟回调
    private void destroy()  {
        if (isDestroyed) {
            return;
        }
        // 回收资源
        activitysMainBinding.liRoot.removeAllViews(); //移除内容显示区域layout
        TbsFileInterfaceImpl.getInstance().closeFileReader(); //关闭fileReader
        isDestroyed = true;
    }









}
